package com.chinemit.cui.remoting
{
	import flash.events.EventDispatcher;
	import flash.events.NetStatusEvent;
	import flash.events.TimerEvent;
	import flash.net.NetConnection;
	import flash.net.Responder;
	import flash.utils.Timer;
	
	[Event(name="result", type="game.remoting.RemoteEvent")]
	[Event(name="fault", type="game.remoting.RemoteEvent")]
	
	public class GameRemote extends EventDispatcher
	{
		private var nc:NetConnection;
		private var timer:Timer;
		
		private var _command:String;
		
		public function GameRemote(command:String, ...parameters)
		{
			_command = command;
			
			timer = new Timer(180000);
			timer.addEventListener(TimerEvent.TIMER, onTimer);
			timer.start();
			
			nc = new NetConnection();
			nc.addEventListener(NetStatusEvent.NET_STATUS, onStatus);
			nc.connect(parameters["CONNECT_URL"],"CommonService");//(Resource.CONNECT_URL + "?ver=test&uid=" + Resource.uid + "&hash=" + Resource.hash);
			var responder:Responder = new Responder(onResult, onFault);
			nc.call(command, responder, parameters);
		}
		
		private function onStatus(e:NetStatusEvent):void
		{
			trace ('"' + _command + '" fault -->', e.info.code);
			timer.removeEventListener(TimerEvent.TIMER, onTimer);
			timer.reset();
			var event:RemoteEvent = new RemoteEvent(RemoteEvent.FAULT);
			event.fault = e.info;
			dispatchEvent(event);
		}
		
		private function onResult(result:*):void
		{
			timer.removeEventListener(TimerEvent.TIMER, onTimer);
			timer.reset();
			var event:RemoteEvent = new RemoteEvent(RemoteEvent.RESULT);
			event.result = result;
			dispatchEvent(event);
		}
		
		private function onFault(fault:*):void
		{
			timer.removeEventListener(TimerEvent.TIMER, onTimer);
			timer.reset();
			trace ('"' + _command + '" fault -->', fault.faultDetail + ",", fault.faultString);
			var event:RemoteEvent = new RemoteEvent(RemoteEvent.FAULT);
			event.fault = fault;
			dispatchEvent(event);
		}
		
		private function onTimer(e:TimerEvent):void
		{
			timer.removeEventListener(TimerEvent.TIMER, onTimer);
			timer.reset();
			nc.close();
			trace ('"' + _command + '" fault --> timeout');
			var event:RemoteEvent = new RemoteEvent(RemoteEvent.FAULT);
			event.fault = '"' + _command + '" timeout';
			dispatchEvent(event);
		}
	}
}